package com.example.demo.dao;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.example.demo.domain.Commodity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.domain.CommodityDTO;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since 2022-10-30
 */
@Mapper
public interface CommodityDao extends BaseMapper<Commodity> {

    @Insert("insert into commodity_suppliers (commodity_id,suppliers_id) values(#{commodityId},#{supplierId})")
    public void insertCommoditySupplier(long commodityId,long supplierId);

    @Delete("delete from commodity_suppliers where commodity_id = #{productId}")
    public void deleteSupplierByCommodity(long commodityId);


    /**
     * 查询条件只有product信息时，进行单表查询
     * @param page
     * @param wrapper
     * @return
     */
    @Select("select distinct p.* from commodity p ${ew.customSqlSegment}")
    @Results({@Result(id = true, property = "id", column = "id"),
            @Result(property = "supplierList", column = "id",
                    many = @Many(select = "com.example.demo.dao.SupplierDao.findSuppliersByCommodity"))})
    public IPage<Commodity> findCommodity(IPage<Commodity> page, @Param(Constants.WRAPPER) QueryWrapper<Commodity> wrapper);
    /**
     * 查询商品，并附带每个商品的供应商
     * 查询结果使用CommodityDto表示。调用另一个mapper方法进行查找来填充CommodityDto.suppliers
     * @return
     */
    /**
     * 查询条件包括supplier信息时，需要多表联合查询
     * @param page
     * @param wrapper
     * @return
     */
    @Select("select distinct p.* from commodity p" +
            " left join commodity_suppliers cs on p.id=cs.commodity_id " +
            " left join supplier s on s.id=cs.suppliers_id " +
            " ${ew.customSqlSegment}") //由QueryWrapper转换
    @Results({@Result(id = true, property = "id", column = "id"),
            @Result(property = "supplierList", column = "id",
                    many = @Many(select = "com.example.demo.dao.SupplierDao.findSuppliersByCommodity"))})
    public IPage<Commodity> findCommodityBySupplier(IPage<Commodity> page, @Param(Constants.WRAPPER) QueryWrapper<Commodity> wrapper);



}
